/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.tag.css;


import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * Class which extracts css embedded in javascript files and outputs it to a jsp
 * page.
 * 
 * @author Joe Maisel
 */
public class CssOutputTag extends BodyTagSupport
{
	private static final long serialVersionUID = 1690154453286387961L;
	private static final String REQUEST_KEY = CssOutputTag.class.getName();

	private boolean output = false;

	@Override
	public int doEndTag() throws JspException
	{
		if( pageContext.getRequest().getAttribute( REQUEST_KEY ) == null )
		{
			pageContext.getRequest().setAttribute( REQUEST_KEY, new StringBuffer() );
		}

		StringBuffer allClasses = (StringBuffer) pageContext.getRequest().getAttribute( REQUEST_KEY );

		if( output )
		{
			try
			{
				pageContext.getOut().println( allClasses.toString() );
				pageContext.getOut().flush();
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
		}
		else
		{
			allClasses.append( "\n\n" + bodyContent.getString() + "\n\n" );
		}

		return super.doEndTag();
	}

	/**
	 * @return the output
	 */
	public boolean isOutput()
	{
		return output;
	}

	/**
	 * @param output
	 *            the output to set
	 */
	public void setOutput( boolean output )
	{
		this.output = output;
	}
}
